import 'dart:async';
import 'package:flutter/services.dart';

class Type {
  static final String GetInfo = "getInfo";
}

class Hello {
  /// 触发安卓原生
  ///
  static const MethodChannel _channel = const MethodChannel('hello');

  static Future<String?> get platformVersion async {
    return await _channel.invokeMethod<String>('getPlatformVersion');
  }

  static Future<double?> handleAdd(double a, double b) async {
    return await _channel.invokeMethod<double>('handleAdd', {
      "a": a,
      "b": b,
    });
  }

  static Future<bool?> registerWxApp() async {
    return await _channel.invokeMethod<bool>('register');
  }

  static Future<bool?> openWxApp() async {
    return await _channel.invokeMethod<bool>('openWxApp');
  }

  static Future<Map<String, dynamic>> getInfo() async {
    Map result = await registerCallback<Map>(Type.GetInfo);
    return Map<String, dynamic>.from(result);
  }

  static Future<List<Map<String, dynamic>>> getListTest() async {
    List<Map>? list = await _channel.invokeListMethod<Map>("getListTest");
    return (list ?? []).map((e) => Map<String, dynamic>.from(e)).toList();
  }

  /// 接受安卓原生
  ///
  static const EventChannel _event = const EventChannel('event');

  // 回调集合
  static final Map<String, Function> callbackMap = {};

  // 注册回调
  static Future<T> registerCallback<T>(String type) {
    Completer<T> c = new Completer<T>();
    callbackMap[type] = (result) {
      c.complete(result as T);
      callbackMap.remove(type);
    };
    _channel.invokeMethod(type);
    return c.future;
  }

  // 开始监听
  static void init() {
    _event.receiveBroadcastStream().listen(
      (obj) {
        // 获取类型
        String type = obj['type'] as String;
        // 获取结果
        Map result = obj['result'] as Map;
        if (callbackMap[type] != null && callbackMap[type] is Function) {
          Function cb = callbackMap[type]!;
          // 触发回调
          cb(result);
        }
      },
    );
  }
}
